package cn.itsource.pethome.system.menu.service.impl;

import cn.itsource.pethome.system.menu.domain.Menu;
import cn.itsource.pethome.system.menu.mapper.MenuMapper;
import cn.itsource.pethome.system.menu.service.IMenuService;
import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.BusinessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-02-01
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    public static final String MENU_LIST = "menuList";
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * @return 菜单树
     */
    @Override
    public List<Menu> getMenuTree() {
        List<Menu> all = menuMapper.findAll();
        ArrayList<Menu> result = new ArrayList<>();
        for (Menu menu : all) {
            if (menu.getParentId() == null){//顶级菜单
                result.add(menu);
            }else {
                for (Menu menu1 : all) {
                    if (Objects.equals(menu1.getId(), menu.getParentId()))
                        menu1.getChildren().add(menu);
                }
            }
        }
        return result;
    }

    @Override
    public void add(Menu menu) {
        if(menu.getParentId() != null){
            if(menu.getName() == null){
                throw new BusinessException("菜单名不能为空");
            }
            if(menu.getComponent() == null){
                throw new BusinessException("组件路径不能为空");
            }
            if(menu.getUrl() == null){
                throw new BusinessException("访问URL不能为空");
            }
            if(menu.getIndex() == null){
                throw new BusinessException("排序不能为空");
            }
        }
        super.add(menu);
        //新增菜单以后，更新数据库的菜单
        redisTemplate.opsForValue().set(MENU_LIST,findAll(),1, TimeUnit.DAYS);
    }

    @Override
    public void update(Menu menu) {
        super.update(menu);
        //修改菜单以后，更新redis数据库的菜单
        redisTemplate.opsForValue().set(MENU_LIST,findAll(),1, TimeUnit.DAYS);
    }

    @Override
    public List<Menu> findFirst() {
        return menuMapper.findFirst();
    }

    @Override
    public List<Menu> findAll() {
        //将菜单存入redis。去redis取菜单，如果有，就直接返回，如果没有，就查数据库
        List<Menu> menus = (List<Menu>)redisTemplate.opsForValue().get(MENU_LIST);
        if(menus == null){
            List<Menu> all = super.findAll();
            redisTemplate.opsForValue().set(MENU_LIST,all,1, TimeUnit.DAYS);
            return all;
        }else {
            return menus;
        }
    }
}
